//
//  SMSCodeManager.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/15.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation

private let smsCodesKey = "SMSCodesKey"

class SMSCode: NSObject, NSCoding {
  var sendTime: Date
  var code: String
  
  init(sendTime: Date, code: String) {
    self.sendTime = sendTime
    self.code = code
  }
  
  required convenience init(coder aDecoder: NSCoder) {
    let sendTime = aDecoder.decodeObject(forKey: "sendTime") as! Date
    let code = aDecoder.decodeObject(forKey: "code") as! String
    self.init(sendTime: sendTime, code: code)
  }
  
  func encode(with aCoder: NSCoder) {
    aCoder.encode(sendTime, forKey: "sendTime")
    aCoder.encode(code, forKey: "code")
  }
}

class SMSCodeManager {
  
  // MARK: - Singleton
  static let shared = SMSCodeManager()
  private init() {
    if let smsCodesData = UserDefaults.standard.object(forKey: smsCodesKey) as? Data,
      let smsCodes = NSKeyedUnarchiver.unarchiveObject(with: smsCodesData) as? [String : SMSCode] {
      self.smsCodes = smsCodes
    } else {
      self.smsCodes = [String: SMSCode]()
      save()
    }
  }
  
  private func save() {
    let data = NSKeyedArchiver.archivedData(withRootObject: smsCodes)
    UserDefaults.standard.set(data, forKey: smsCodesKey)
    UserDefaults.standard.synchronize()
  }
  
  private var smsCodes: [String: SMSCode]!
  
  func save(forPhoene: String, smsCode: SMSCode) {
    smsCodes[forPhoene] = smsCode
    save()
  }
  
  func getSmsCode(forPhone: String) -> SMSCode? {
    return smsCodes[forPhone]
  }
}

extension SMSCodeManager {
  static let maxResendSeconds = 30
}
